//
//  IvanTabBar.m
//  YuchBox
//
//  Created by Ivan on 11-9-29.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "IvanTabBar.h"
#define DEVICE_WIDTH    320.0
#define DEVICE_HEIGHT   480.0

#define TAB_ARROW_IMAGE_TAG 2394859
#define SELECTED_VIEW_CONTROLLER_TAG 2394860

#define SEQUENCE_BUFFER_SIZE    6
static int sequence_buffer[SEQUENCE_BUFFER_SIZE] = {0};
static unsigned int seq_index = 0;
//static unsigned int seq_tail = 0;
@implementation IvanTabBar
@synthesize barSize = _barSize;
@synthesize backgroudImage = _backgroudImage;
//@synthesize items = _items;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

//- (void)initWithItemCount:(NSInteger)itemCount 
- (id)initWithItemCount:(NSInteger)itemCount 
                  Items:(NSMutableArray *)items 
 BackgroudImageFileName:(NSString *)backgroudImageFileName 
        AutoSizeByImage:(BOOL)isAutoSize 
               barFrame:(CGRect)barFrame
     ArrowImageFileName:(NSString *)arrowImageFileName
               Delegate:(UIViewController *)delegate
{
    if (self = [super init])
    {
        _backgroudImage = [UIImage imageNamed:backgroudImageFileName]; 
        _arrowImage     = [UIImage imageNamed:arrowImageFileName];
        // set the tabbar size
        self.barSize = isAutoSize ? _backgroudImage.size : barFrame.size;
        
        // set the iteams
        _items = [[NSMutableArray alloc] initWithCapacity:itemCount];
        for (NSMutableDictionary *obj in items) {
            //UIViewController * viewtmp = [obj objectForKey:@"viewcontroller"
            [_items addObject:obj];
        }
        
        // set delegate
        _delegate = delegate;
        
        // draw the backgroud use bitmap piant
        UIGraphicsBeginImageContext(_barSize);

        [_backgroudImage drawInRect:CGRectMake(0.0, 0.0, _barSize.width, _barSize.height)];
        // Create a stretchable image for the top of the background and draw it
        //UIImage* stretchedTopImage = [_backgroudImage stretchableImageWithLeftCapWidth:0 topCapHeight:0];
        //[stretchedTopImage drawInRect:CGRectMake(0, 0, _barSize.width, _barSize.height)];
        
        // Draw a solid black color for the bottom of the background
        //[[UIColor blackColor] set];
        //CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, _barSize.height, _barSize.width, _barSize.height));
        //UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        UIImageView *backgroudImageView = [[UIImageView alloc] initWithImage:_backgroudImage];
        backgroudImageView.frame = CGRectMake(0, 0, _barSize.width, _barSize.height);
        [self addSubview:backgroudImageView];
        [backgroudImageView release];
        
        //self.frame = CGRectMake(0, 0, DEVICE_WIDTH, _barSize.height);
        
        // Initalize the array we use to store our buttons
        _buttons = [[NSMutableArray alloc] initWithCapacity:itemCount];
        
        // horizontalOffset tracks the proper x value as we add buttons as subviews
        float horizontalOffset = 0;
        
        float itemSizeWidth = _barSize.width/itemCount;
        // Iterate through each item
        for (NSUInteger i = 0 ; i < itemCount ; i++)
        {
            // Create a button
           // UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
           // button.frame = CGRectMake(0.0, 0.0, itemSizeWidth, _barSize.height);
            
           // UIImage* rawButtonImage = [self imageAtIndex:i];
           // [button setImage:rawButtonImage forState:UIControlStateNormal];
           // button.adjustsImageWhenHighlighted = NO;

            UIButton* button = [self buttonAtIndex:i width:itemSizeWidth];
            
            // Register for touch events
            [button addTarget:self action:@selector(touchDownAction:) forControlEvents:UIControlEventTouchDown];
            //[button addTarget:self action:@selector(touchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
            //[button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchUpOutside];
            //[button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchDragOutside];
            //[button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchDragInside];
            
            // Add the button to our buttons array
            [_buttons addObject:button];
            
            // Set the button's x offset
            button.frame = CGRectMake(horizontalOffset, 0.0, button.frame.size.width, button.frame.size.height);
            
            // Add the button as our subview
            [self addSubview:button];
            
            if (i == 0) {
                [self touchDownAction:button];
            }
            
            // Advance the horizontal offset
            horizontalOffset = horizontalOffset + itemSizeWidth;
        }

        
        //DEVICE_HEIGHT - _barSize.height
        self.frame = barFrame;// CGRectMake(0.0, DEVICE_HEIGHT - _barSize.height, DEVICE_WIDTH, _barSize.height);
        
        // set the arrow on the top of first button(index 0)
        [self addTabBarArrowAtIndex:-1];
    }
    
    //UIButton * initButton = (UIButton *)[_buttons objectAtIndex:0];
//    
//    if (nil != initButton) {
//        [self touchDownAction:initButton];
//    }
    
    return self;
    
}


// get the image
- (UIImage *)imageAtIndex:(NSInteger)index
{
    NSMutableDictionary *data = [_items objectAtIndex:index];
    
    return [UIImage imageNamed:[data objectForKey:@"image"]];
}

- (UIViewController *)viewControllerAtIndex:(NSInteger)index
{
    NSDictionary* data = [_items objectAtIndex:index];
    UIViewController* viewController = [data objectForKey:@"viewController"];
    
    return viewController;
}


// get the button
- (UIButton*) buttonAtIndex:(NSUInteger)itemIndex width:(float)width
{
    // Create a new button with the right dimensions
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0.0, 0.0, width, _barSize.height);
    
    // Ask the delegate for the button's image
    UIImage* rawButtonImage = [self imageAtIndex:itemIndex];
    // Create the normal state image by converting the image's background to gray
   // UIImage* buttonImage = [self tabBarImage:rawButtonImage size:button.frame.size backgroundImage:nil];
    // And create the pressed state image by converting the image's background to the background image we get from the delegate
   // UIImage* buttonPressedImage = [self tabBarImage:rawButtonImage size:button.frame.size backgroundImage:[delegate selectedItemBackgroundImage]];
    
    // Set the gray & blue images as the button states
    [button setImage:rawButtonImage forState:UIControlStateNormal];
//    [button setBac   kgroundImage:rawButtonImage forState:UIControlStateNormal];
  //  [button setImage:buttonPressedImage forState:UIControlStateHighlighted];
   // [button setImage:buttonPressedImage forState:UIControlStateSelected];
    
    // Ask the delegate for the highlighted/selected state image & set it as the selected background state
    //[button setBackgroundImage:[delegate selectedItemImage] forState:UIControlStateHighlighted];
    //[button setBackgroundImage:[delegate selectedItemImage] forState:UIControlStateSelected];
    
    button.adjustsImageWhenHighlighted = NO;
    
    return button;
}

- (void)touchDownAction:(UIButton *)button
{
    [self dimAllButtonsExcept:button];
    
    // Remove the current view controller's view
    
//    UIView* currentView = [_delegate.view viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];
    // Get the right view controller
    NSUInteger index = [_buttons indexOfObjectIdenticalTo:button];
    NSDictionary* data = [_items objectAtIndex:index];
    UIViewController<IvanTabBarDelegate>* viewController = [data objectForKey:@"viewController"];
    
    if (_currentDelegate == viewController) {
        return;
    }
    
    IVAN_SEL_OBJ(_currentDelegate, viewWillDisappearIvan, NO);
    [_currentDelegate.view removeFromSuperview];
    IVAN_SEL_OBJ(_currentDelegate, viewDidDisappearIvan, NO);
    
    // Use the TabBarGradient image to figure out the tab bar's height (22x2=44)
    //UIImage* tabBarGradient = [UIImage imageNamed:@"TabBarGradient.png"];
    
    // Set the view controller's frame to account for the tab bar
//    viewController.view.frame = CGRectMake(0, 0, _barSize.width, DEVICE_HEIGHT - _barSize.height);
    
    // Se the tag so we can find it later
//    viewController.view.tag = SELECTED_VIEW_CONTROLLER_TAG;
    
    // Add the new view controller's view
   // [_delegate.view addSubview:viewController.view];
    
    // WARNING for the squence show
    Boolean isHidden = NO;
    seq_index %= SEQUENCE_BUFFER_SIZE;
    sequence_buffer[seq_index++] = index + 1;
    
    if ([viewController respondsToSelector:@selector(showViewSequence)]) {
        NSInteger sequence = [viewController showViewSequence];
        NSInteger sequenceNumber = 0;
        
        int seqIndex = seq_index - 1;
        
        sequenceNumber = sequence & 0x0000000F;
        if (sequenceNumber == index + 1) {            
            while (0 != sequenceNumber) {
                if (sequence_buffer[seqIndex] == sequenceNumber) {
                    isHidden = NO;
                } else {
                    isHidden = YES;
                    break;
                }
                
                seqIndex = seqIndex == 0 ? SEQUENCE_BUFFER_SIZE : seqIndex;
                seqIndex--;
                sequence >>= 4;
                sequenceNumber = sequence & 0x0000000F;
            }
            
            for (UIView *subView in viewController.view.subviews) {
                subView.hidden = isHidden;
            }
        }
    }
    
    if (!isHidden) {
//        [viewController viewWillAppear:NO];
        IVAN_SEL_OBJ(viewController, viewWillAppearIvan, NO);
    }
    
    [_delegate.view insertSubview:viewController.view atIndex:0];
    
    if (!isHidden) {
        IVAN_SEL_OBJ(viewController, viewDidAppearIvan, NO);
//        [viewController viewDidAppear:NO];
    }
    
    _currentDelegate = viewController;
    

    // In 1 second glow the selected tab
  //  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(addGlowTimerFireMethod:) userInfo:[NSNumber numberWithInteger:itemIndex] repeats:NO];

}

- (float) horizontalLocationFor:(NSUInteger)tabIndex
{
    UIImageView* tabBarArrow = (UIImageView*)[self viewWithTag:TAB_ARROW_IMAGE_TAG];
    
    // A single tab item's width is the entire width of the tab bar divided by number of items
    float tabItemWidth = _barSize.width / _buttons.count;
    // A half width is tabItemWidth divided by 2 minus half the width of the arrow
    float halfTabItemWidth = (tabItemWidth / 2.0) - (tabBarArrow.frame.size.width / 2.0);
    
    // The horizontal location is the index times the width plus a half width
    return (tabIndex * tabItemWidth) + halfTabItemWidth;
}

- (void) addTabBarArrowAtIndex:(NSUInteger)itemIndex
{
 //   UIImage* tabBarArrowImage = [delegate tabBarArrowImage];
    UIImageView* tabBarArrow = [[UIImageView alloc] initWithImage:_arrowImage];
    tabBarArrow.tag = TAB_ARROW_IMAGE_TAG;
    
    // To get the vertical location we go up by the height of arrow and then come back down 2 pixels so the arrow is slightly on top of the tab bar.
    tabBarArrow.frame = CGRectMake([self horizontalLocationFor:itemIndex], -5, _arrowImage.size.width, _arrowImage.size.height);
    
    [self addSubview:tabBarArrow];
    [tabBarArrow release];
}

-(void) dimAllButtonsExcept:(UIButton*)selectedButton
{
    
    UIImageView* tabBarArrow = (UIImageView*)[self viewWithTag:TAB_ARROW_IMAGE_TAG];
    NSUInteger selectedIndex = [_buttons indexOfObjectIdenticalTo:selectedButton];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    
    CGRect frame = tabBarArrow.frame;
    frame.origin.x = [self horizontalLocationFor:selectedIndex];
    tabBarArrow.frame = frame;
    [UIView commitAnimations];
    
}

- (void)dealloc
{
    [_buttons release];
    [_items release];
    [super dealloc];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
